package com.itxiuyixiu.entity.component;

import com.itxiuyixiu.entity.enums.AuthorityType;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * @author 黄磊
 * @date 2020/6/2
 */
public class AuthorityValidatorImpl implements ConstraintValidator<AuthorityValidator, String> {
    private static final ArrayList<String> AUTHORITIES = new ArrayList<>();

    static {
        try {
            AuthorityType authorityType = new AuthorityType();
            Field[] fields = AuthorityType.class.getFields();
            for (Field field : fields) {
                AUTHORITIES.add((String) field.get(authorityType));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(AuthorityValidator constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || "".equals(value)) {
            return true;
        }
        String[] strings = value.split(",");
        for (int i = 0; i < strings.length; i++) {
            for (int j = i + 1; j < strings.length; j++) {
                if (strings[i].equals(strings[j])) {
                    return false;
                }
            }
            if (!AUTHORITIES.contains(strings[i])) {
                return false;
            }
        }
        return true;
    }
}
